package com.abel.web.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.abel.domain.Application;
import com.abel.domain.PersonalInformation;
import com.abel.manager.PersonProfileManager;
import com.abel.manager.exception.PersonProfileException;
import com.abel.util.UserSessionLocator;
import com.abel.web.view.PersonalInfoViewBean;

public class PersonalInformationController extends SimpleFormController {

        protected final Log logger = LogFactory.getLog(getClass());
        
        private PersonProfileManager personProfileManager;

        @Override
        protected ModelAndView onSubmit(
                HttpServletRequest request,
                HttpServletResponse response,
                Object command,
                BindException errors) throws Exception
        {
            PersonalInformation personalInformation = new PersonalInformation();
            ModelAndView mav = null;
            this.convertViewToPersonalInformation(personalInformation, (PersonalInfoViewBean)command);
            try {
            	
				this.personProfileManager.updatePersonalInfo(personalInformation);
			
            } 
            catch (PersonProfileException e) {

    			logger.error("@PersonalInformationController : onSubmit : Duplicate user exception " + e);
    			errors.rejectValue("", "error.null",null,"A system error occurred while registering your information. Please log out and log back in.");
    			return showForm(request,response,errors);
			}
            catch (Exception e) {

    			logger.error("@PersonalInformationController : onSubmit : exception " + e);
    			errors.rejectValue("", "error.null",null,"A system error occurred while registering your information. Please log out and log back in.");
    			return showForm(request,response,errors);

            }
            mav = new ModelAndView("redirect:" + getSuccessView());
            return mav;
        }


        @Override
        protected Object formBackingObject(HttpServletRequest request)
                throws Exception
        {
        	String userName = UserSessionLocator.getUserSession().getAuthPrincipal().getUserName();
        	
        	PersonalInfoViewBean viewBean = new PersonalInfoViewBean();
        	viewBean.setUserName(userName);
        	
        	
        	Application application = UserSessionLocator.getUserSession().getPerson().getApplication();
        	
        	if (application.getPersonProfile().getPersonalInformation() != null) {
        		
        		PersonalInformation personalInformation = application.getPersonProfile().getPersonalInformation();
        		viewBean.setFirstName(personalInformation.getFirstName());
        		viewBean.setMi(personalInformation.getMiddleName());
        		viewBean.setLastName(personalInformation.getLastName());
        		viewBean.setSsn(personalInformation.getSsn());
        		viewBean.setAddress1(personalInformation.getAddressLine1());
        		viewBean.setAddress2(personalInformation.getAddressLine2());
        		viewBean.setCity(personalInformation.getCity());
        		viewBean.setState(personalInformation.getState());
        		viewBean.setZip(personalInformation.getZip());
        		viewBean.setHomePhone(personalInformation.getHomePhone());
        		viewBean.setAltPhone(personalInformation.getAlternatePhone());
        		viewBean.setWorkPhone(personalInformation.getWorkPhone());
        		viewBean.setEmergencyContact(personalInformation.getEmergencyContact());
        		viewBean.setEmergencyContactPhone(personalInformation.getEmergencyContactPhone());
        		viewBean.setEmergencyContactRelation(personalInformation.getEmergencyContactRelation());
        		
        		//setting date of birth
        		if (personalInformation.getDateOfBirth() != null) {
        			viewBean.setDateOfBirth(new SimpleDateFormat("MM/dd/yyyy").format(personalInformation.getDateOfBirth()));
        		}
        	}
        	return viewBean;
        }

        /**
         * @param personProfileManager the personProfileManager to set
         */
        public void setPersonProfileManager(PersonProfileManager personProfileManager)
        {
            this.personProfileManager = personProfileManager;
        }
        
        
        private void convertViewToPersonalInformation(PersonalInformation personalInformation, PersonalInfoViewBean viewBean) 
        	throws Exception {
        	
        	personalInformation.setFirstName(viewBean.getFirstName());
        	personalInformation.setMiddleName(viewBean.getMi());
        	personalInformation.setLastName(viewBean.getLastName());
        	personalInformation.setSsn(viewBean.getSsn());
        	
        	try {
        		if (viewBean.getDateOfBirth() != null) {
				personalInformation.setDateOfBirth(new SimpleDateFormat("MM/dd/yyyy").parse(viewBean.getDateOfBirth()));
        		}
			} 
        	catch (ParseException e) {
				
        		e.printStackTrace();
				throw new Exception(e);
			}
        	personalInformation.setAddressLine1(viewBean.getAddress1());
        	personalInformation.setAddressLine2(viewBean.getAddress2());
        	personalInformation.setCity(viewBean.getCity());
        	personalInformation.setState(viewBean.getState());
        	personalInformation.setZip(viewBean.getZip());
        	personalInformation.setHomePhone(viewBean.getHomePhone());
        	personalInformation.setAlternatePhone(viewBean.getAltPhone());
        	personalInformation.setWorkPhone(viewBean.getWorkPhone());
        	personalInformation.setEmergencyContact(viewBean.getEmergencyContact());
        	personalInformation.setEmergencyContactPhone(viewBean.getEmergencyContactPhone());
        	personalInformation.setEmergencyContactRelation(viewBean.getEmergencyContactRelation());
      
        }
 
        


}
